package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.util.NumberUtils;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Override
    public boolean isAsync() {
        return false;
    }


    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        List<CartProductDto> productDtoList = createOrderContext.getCartProductDtoList();
        List<Long> goodIds = productDtoList.stream().map(a -> a.getProductId()).collect(Collectors.toList());
        createOrderContext.setBuyProductIds(goodIds);

        //生成订单号
        String orderId = null;

        orderId = globalIdGeneratorUtil.getNextSeq("orderId", 1);
        createOrderContext.setOrderId(orderId);

        Order order = new Order();
        order.setOrderId(orderId);
        order.setBuyerNick(createOrderContext.getUserName());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setPaymentType(1);
       //邮费 order.setPostFee();
        order.setStatus(0);
        Date date = new Date();
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setShippingName("京东快递");
        //TODO:拿订单号
        //order.setShippingCode(UUID.randomUUID().toString());
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getUserName());
        try {
            orderMapper.insertSelective(order);
        } catch (Exception e) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                    OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }

        //向订单商品表中插入n条数据
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {

            OrderItem orderItem = new OrderItem();


            String orderItemId = globalIdGeneratorUtil.getNextSeq("orderItemId", 1);
            orderItem.setId(orderItemId);


            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            int num = cartProductDto.getProductNum().intValue();
            orderItem.setNum(num);
            orderItem.setTitle(cartProductDto.getProductName());
            double price = NumberUtils.toDouble(cartProductDto.getSalePrice());
           // BigDecimal salePrice = cartProductDto.getSalePrice();
            orderItem.setPrice(price);

            BigDecimal numDecimal = new BigDecimal(num);

           // orderItem.setTotalFee(salePrice.multiply(numDecimal));
            orderItem.setTotalFee(price*num);
            orderItem.setPicPath(cartProductDto.getProductImg());
            orderItem.setStatus(1);
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            try {
                orderItemMapper.insertSelective(orderItem);
            } catch (Exception e) {
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(),
                        OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }
        }
        return true;
    }

}
